﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.RBAC;
using B.S.BasicData.Domian.Entities;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.RBAC
{
    public class DelUserRoleHandler : IRequestHandler<DelUserRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserRoleModel> userroleRepo;
        private readonly IMapper mapper;

        public DelUserRoleHandler(IBaseRepository<UserRoleModel>userroleRepo,IMapper mapper)
        {
            this.userroleRepo = userroleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelUserRoleCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();
            var user= userroleRepo.GetAll().Where(x=>x.UserId==request.UserId && x.RoleId==request.RoleId).FirstOrDefault();
            var entity=mapper.Map<UserRoleModel>(user);
            var r=userroleRepo.Delete(entity).Result;  
            if (r > 0)
            {
                res.Message = "删除成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "删除失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
